package com.feishi.core.office.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FreemarkerUtil {
    public static void main(String[] args) throws IOException, TemplateException, ParseException {
        Map<String,Object> dataMap = new HashMap<String, Object>();

        List<Map<String,Object>> list=new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            Map<String,Object> item=new HashMap<>();
            item.put("index",i+1);
            item.put("name","[CT ASPHINA 509MCN] dpt 01.5");
            item.put("sn","1S21064204"+(50+i));
            item.put("validityPeriod","2030-08-21");
            item.put("pickTime","8-21 11:13");
            list.add(item);
        }
        dataMap.put("list",list);
        dataMap.put("printUser","护士A");
        dataMap.put("printTime","2021-08-21 19:06");
        dataMap.put("statisticalTime","2021-08-21~2021-08-21");
        //以utf-8的编码读取ftl文件
        Template template = getTemplate("D:/out.xml");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/out.docx"), "utf-8"), 10240);
        template.process(dataMap, out);
        out.close();

    }
    public static Template getTemplate(String filePath){
        URL uri = Thread.currentThread().getContextClassLoader().getResource(filePath);
        if (uri!=null){
            filePath=uri.getFile();
        }
        File file=new File(filePath);
        if(file.getParentFile()!=null){
            return getTemplate(file.getName(),file.getParentFile());
        }
        return null;
    }
    public static Template getTemplate(String fileName,File baseDir){
        Configuration configuration = new Configuration(new Version("2.3.31"));
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(baseDir);
            return configuration.getTemplate(fileName, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
